package com.autonavi.collapse.config;

import com.autonavi.collapse.task.model.ExtendedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StaticConfigManager implements ConfigManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(StaticConfigManager.class);
    private Map<String, ExtendedMap> configMap = new HashMap<>();
    private File baseDir;
    private Map<String, ConfigLoader> loaders = new HashMap<>();
    private ConfigLoader defaultLoader;

    public StaticConfigManager() {

    }

    //需要在resources/classpath目录下配置xml，鸡肋，去除
    public StaticConfigManager(String basePath) {
        if (basePath == null) {
            throw new IllegalArgumentException("basePath is empty");
        }
        if (basePath.startsWith("classpath")) {
            URL resource = getClass().getClassLoader().getResource(basePath.replace("classpath:",""));
            if (resource == null) {
                throw new IllegalArgumentException("basePath not in classpath");
            }
            baseDir = new File(basePath);
        } else {
            this.baseDir = new File(basePath);
        }
        XmlConfigLoader defaultLoader = new XmlConfigLoader();
        loaders.put("xml",defaultLoader);
        this.defaultLoader = defaultLoader;
    }

    @Override
    public void init() throws Exception {
        if (baseDir != null) {
            File[] files = baseDir.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isFile()) {
                        String name = file.getName();
                        int index = name.lastIndexOf(".");
                        String typeName = null;
                        if (index > 0) {
                            typeName = name.substring(index + 1);
                        }
                        ConfigLoader configLoader = loaders.get(typeName);
                        if (configLoader == null) {
                            configLoader = defaultLoader;
                        }
                        List<ExtendedMap> extendedMaps = configLoader.load(file);
                        if (extendedMaps != null) {
                            for (ExtendedMap extendedMap : extendedMaps) {
                                configMap.put(extendedMap.getName(), extendedMap);
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public ExtendedMap findConfig(String name) {
        return configMap.get(name);
    }
}
